package MementoMod;

import java.util.Stack;

public class code {
    // 备忘录类
    class Memento {
        private String state;

        public Memento(String state) {
            this.state = state;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }
    }

    // 照顾者类
    class CareTaker {
        private Stack<Memento> undoStack = new Stack<>();
        private Stack<Memento> redoStack = new Stack<>();

        public void addMemento(Memento memento) {
            undoStack.push(memento);
            redoStack.clear(); // 重做栈清空，因为新的状态已经保存，之前的重做步骤不再有效
        }

        public Memento redo() {
            return redoStack.empty() ? null : redoStack.pop();
        }

        public Memento undo() {
            Memento memento = undoStack.empty() ? null : undoStack.pop();
            if (memento != null) {
                redoStack.push(memento); // 将撤销的状态推入重做栈
            }
            return memento;
        }
    }

    // 编辑器类
    class TextEditor {
        private String state;
        private CareTaker careTaker;

        public TextEditor(CareTaker careTaker) {
            this.careTaker = careTaker;
        }

        public void setState(String state) {
            this.state = state;
            careTaker.addMemento(new Memento(state)); // 每次状态改变时，保存当前状态
        }

        public String getState() {
            return state;
        }

        public void undo() {
            Memento memento = careTaker.undo();
            if (memento != null) {
                this.state = memento.getState();
            }
        }

        public void redo() {
            Memento memento = careTaker.redo();
            if (memento != null) {
                this.state = memento.getState();
            }
        }

        public void createMemento() {
            // 这个方法可以根据需要创建备忘录，例如在初始化时或者特定操作前
            careTaker.addMemento(new Memento(state));
        }
    }
}
